package com.atguigu.tingshu.order.delay;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author atguigu-mqx
 * @ClassName RedisDelayHandle
 * @description: TODO
 * @date 2023年11月10日
 * @version: 1.0
 */
@Slf4j
@Component
public class RedisDelayHandle {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoService orderInfoService;

    //  xxl-job:分布式定时任务调度框架!

    //    @Scheduled(cron = "0/1 * * * * ?")
    //    public void orderCancel(){
    //        System.out.println("来人了，开始接客了....");
    //    }

    //    public void cancel(){
    //        Timer timer = new Timer();
    //        timer.schedule(new TimerTask() {
    //            @Override
    //            public void run() {
    //                //  业务逻辑
    //            }
    //        }, 10);
    //    }


    //  监听延迟消息.
    @PostConstruct
    public void getMsg() {
        //  循环：
        new Thread(() -> {
            while (true) {
                //  获取数据.
                RBlockingQueue<Object> blockingQueue = redissonClient.getBlockingQueue(KafkaConstant.QUEUE_ORDER_CANCEL);
                //  调用方法获取队列中的数据.
                try {
                    String orderId = (String) blockingQueue.take();
                    //  判断
                    if (!StringUtils.isEmpty(orderId)) {
                        //  取消订单.
                        orderInfoService.orderCancel(Long.parseLong(orderId));
                        log.info("执行取消订单");
                    }
                } catch (InterruptedException e) {
                    //  异常信息
                    log.error("异常信息." + e.getMessage());
                    throw new RuntimeException(e);
                }
            }
        }).start();
        //  Spring Task
    }
}
